<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="taskNo">
        <el-input
          v-model="queryParams.taskNo"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="applicantName">
        <el-input
          v-model="queryParams.applicantName"
          placeholder="请输入申请人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请时间" prop="applyTime">
        <el-date-picker
          clearable
          v-model="queryParams.applyTime"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="单据类别" prop="todoType">
        <el-select
          v-model="queryParams.todoType"
          placeholder="请选择"
          clearable
          @change="handleQuery"
        >
          <el-option label="入住" value="入住" />
          <el-option label="退住" value="退住" />
          <el-option label="请假" value="请假" />
        </el-select>
      </el-form-item>
      <el-form-item label="流程状态" prop="processStatus">
        <el-select
          v-model="queryParams.processStatus"
          placeholder="请选择"
          clearable
          @change="handleQuery"
        >
          <el-option label="申请中" value="申请中" />
          <el-option label="已完成" value="已完成" />
          <el-option label="已关闭" value="已关闭" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 状态切换滑块（按钮组样式） -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="24">
        <el-button-group>
          <el-button 
            :type="tabType === '0' ? 'primary' : 'default'" 
            @click="tabType = '0'; handleTabChange()"
            icon="Clock"
          >待处理</el-button>
          <el-button 
            :type="tabType === '1' ? 'primary' : 'default'" 
            @click="tabType = '1'; handleTabChange()"
            icon="Check"
          >已处理</el-button>
        </el-button-group>
      </el-col>
    </el-row>

    <!-- 列表区域 -->
    <el-table v-loading="loading" :data="filteredTaskList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" type="index" align="center" width="50" />
      <el-table-column label="单据编号" align="center" prop="taskNo" />
      <el-table-column label="单据标题" align="center" prop="taskTitle" />
      <el-table-column label="单据类别" align="center" prop="todoType" />
      <el-table-column label="申请人" align="center" prop="applicantName" />
      <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applyTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="等待时长" align="center" prop="waitTime" />
      <el-table-column label="流程状态" align="center" prop="processStatus">
        <template #default="scope">
          <el-tag v-if="scope.row.processStatus === '申请中'" type="info">{{ scope.row.processStatus }}</el-tag>
          <el-tag v-else-if="scope.row.processStatus === '已完成'" type="success">{{ scope.row.processStatus }}</el-tag>
          <el-tag v-else type="warning">{{ scope.row.processStatus }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:task:edit']">处理</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 处理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="taskRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="单据编号" prop="taskNo">
          <el-input v-model="form.taskNo" disabled />
        </el-form-item>
        <el-form-item label="单据标题" prop="taskTitle">
          <el-input v-model="form.taskTitle" disabled />
        </el-form-item>
        <el-form-item label="流程状态" prop="processStatus">
          <el-select v-model="form.processStatus" placeholder="请选择处理结果">
            <el-option label="已完成" value="已完成" />
            <el-option label="已关闭" value="已关闭" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理备注" prop="handleRemark">
          <el-input v-model="form.handleRemark" placeholder="请输入处理备注" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Task">
import { listTask, getTask, updateTask } from "@/api/system/task"
import { parseTime } from "@/utils/date"

const { proxy } = getCurrentInstance()

// 响应式数据
const taskList = ref([]) // 原始数据列表
const filteredTaskList = ref([]) // 滑块筛选后的数据列表
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const title = ref("")
const tabType = ref("0") // 0-待处理(申请中)，1-已处理(非申请中)

const data = reactive({
  form: {
    id: null,
    taskNo: null,
    taskTitle: null,
    processStatus: null,
    handleRemark: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskNo: null,
    todoType: null,
    applicantName: null,
    applyTime: null,
    processStatus: null
  },
  rules: {
    processStatus: [
      { required: true, message: "请选择处理结果", trigger: "change" }
    ],
    handleRemark: [
      { required: true, message: "请输入处理备注", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询原始列表并根据滑块筛选 */
function getList() {
  loading.value = true
  listTask(queryParams.value).then(response => {
    // 1. 保存原始数据和总条数
    taskList.value = response.rows.map(item => ({
      ...item,
      // 字段映射：TodoTask 表字段
      processStatus: item.processStatus || '申请中',
      taskNo: item.taskNo || '',
      taskTitle: item.taskTitle || '',
      todoType: item.todoType || '',
      applicantName: item.applicantName || '',
      applyTime: item.applyTime,
      // 计算等待时长
      waitTime: calculateWaitTime(item.applyTime)
    }))
    total.value = response.total

    // 2. 根据当前滑块状态筛选数据
    filterTaskList()

    loading.value = false
  }).catch(error => {
    console.error('获取待办事项列表失败:', error)
    loading.value = false
  })
}

/** 根据滑块状态筛选数据（核心逻辑） */
function filterTaskList() {
  if (tabType.value === '0') {
    // 待处理：只显示流程状态为“申请中”的数据
    filteredTaskList.value = taskList.value.filter(item => item.processStatus === '申请中')
  } else {
    // 已处理：只显示流程状态不为“申请中”的数据
    filteredTaskList.value = taskList.value.filter(item => item.processStatus !== '申请中')
  }
}

/** 滑块切换时重新筛选数据 */
function handleTabChange() {
  filterTaskList()
}

/** 计算等待时长 */
function calculateWaitTime(applyTime) {
  if (!applyTime) return '未知'
  const applyDate = new Date(applyTime).getTime()
  const now = new Date().getTime()
  const diffSeconds = Math.floor((now - applyDate) / 1000)
  
  if (diffSeconds < 60) return `${diffSeconds}秒`
  if (diffSeconds < 3600) return `${Math.floor(diffSeconds / 60)}分钟${diffSeconds % 60}秒`
  if (diffSeconds < 86400) return `${Math.floor(diffSeconds / 3600)}小时${Math.floor((diffSeconds % 3600) / 60)}分钟`
  return `${Math.floor(diffSeconds / 86400)}天${Math.floor((diffSeconds % 86400) / 3600)}小时`
}

/** 搜索事件 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置搜索 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 处理按钮点击 */
function handleUpdate(row) {
  resetForm()
  getTask(row.id).then(response => {
    const data = response.data
    form.value = {
      id: data.id,
      taskNo: data.taskNo,
      taskTitle: data.taskTitle,
      processStatus: data.processStatus,
      handleRemark: ''
    }
    open.value = true
    title.value = "处理待办单据"
  })
}

/** 提交处理结果 */
function submitForm() {
  proxy.$refs["taskRef"].validate(valid => {
    if (valid) {
      form.value.completeTime = new Date().toISOString() // 补充完成时间
      updateTask(form.value).then(() => {
        proxy.$modal.msgSuccess("处理成功")
        open.value = false
        getList() // 重新加载列表
      })
    }
  })
}

/** 取消处理 */
function cancel() {
  open.value = false
  resetForm()
}

/** 重置表单 */
function resetForm() {
  form.value = {
    id: null,
    taskNo: null,
    taskTitle: null,
    processStatus: null,
    handleRemark: null
  }
  proxy.resetForm("taskRef")
}

/** 选择项变化（预留） */
function handleSelectionChange(selection) {
  // 暂无需实现
}

// 初始化加载数据
getList()
</script>4